package com.study.nacos.nacosstudy.service;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.UrlCleaner;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description :
 * @Version : V1.0.0
 * @Date : 2022/8/17 16:54
 */
@Service
public class CustomUrlBlockHandler implements BlockExceptionHandler, UrlCleaner {

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
        httpServletResponse.setHeader("Content-Type", "application/json;charset=UTF-8");
        String message = "{\"code\":999,\"msg\":\"访问人数过多\"}";
        httpServletResponse.getWriter().write(message);
    }

    @Override
    public String clean(String s) {
        if (StringUtils.isEmpty(s)) {
            return s;
        }
        if (s.startsWith("/clean/")) {
            return "/clean/*";
        }
        return s;
    }
}
